package com.lzh.seatrend.config.datasource.mysqlDataSource;

import com.github.pagehelper.PageInterceptor;
import com.lzh.seatrend.config.datasource.BaseConfig;
import com.lzh.seatrend.util.seatrend.AesUtil;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @Classname SecondDataSourceConfig
 * @Description mysql数据库
 * @Date 2021/11/29 14:10
 * @Created by liuzihao
 */
@Configuration
//@MapperScan
public class SecondDataSourceConfig {

    @Value("${spring.datasource.datasource2.url}")
    private String url;

    @Value("${spring.datasource.datasource2.username}")
    private String username;

    @Value("${spring.datasource.datasource2.password}")
    private String password;

    @Value("${spring.datasource.datasource2.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.maximum-pool-size}")
    private int maximumPoolSize;
    @Value("${spring.datasource.max-idle}")
    private int maxIdle;
    @Value("${spring.datasource.min-idle}")
    private int minIdle;
    @Value("${spring.datasource.initial-size}")
    private int initialSize;
    @Value("${spring.datasource.validation.query}")
    private String validationQuery;
    @Value("${spring.datasource.test-on-borrow}")
    private boolean testOnBorrow;
    @Value("${spring.datasource.test-while-idle}")
    private boolean testWhileIdle;
    @Value("${spring.datasource.time-between-eviction-runs-millis}")
    private long timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.max-wait}")
    private long maxWait;

    /**
     * 数据库连接池配置
     *
     * @return
     * @Primary 设置多实现类的默认调用
     */
    @Bean(name = "dataSourceSecond")
    @Primary
    public DataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(driverClassName);
        try {
            if (BaseConfig.IS_ENCRYPT_DATA) {
                url = AesUtil.decrypt(url, BaseConfig.ENCRYPT_KEY);
                username = AesUtil.decrypt(username, BaseConfig.ENCRYPT_KEY);
                password = AesUtil.decrypt(password, BaseConfig.ENCRYPT_KEY);
            }
        } catch (Exception e) {
            e.printStackTrace();
            url = "";
            username = "";
            password = "";
        }
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setMaxTotal(maximumPoolSize);
        ds.setValidationQuery(validationQuery);
        ds.setInitialSize(initialSize);
        ds.setMaxIdle(maxIdle);
        ds.setMinIdle(minIdle);
        ds.setTestOnBorrow(testOnBorrow);
        ds.setTestWhileIdle(testWhileIdle);
        ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        ds.setMaxWaitMillis(maxWait);
        return ds;
    }

    @Bean(name = "sqlSessionFactorySecond")
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSourceSecond") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        //分页插件配置
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("params", "pageNum=page;pageSize=size");
        properties.setProperty("returnPageInfo", "true");
        properties.setProperty("params", "count=countSql");
        pageInterceptor.setProperties(properties);

        //添加插件
        bean.setPlugins(new Interceptor[]{pageInterceptor});

        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(resolver.getResources("classpath:secondmapper/*.xml"));
            bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Bean(name = "transactionManagerSecondSecond")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSourceSecond") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionTemplateSecondSecond")
    @Primary
    public SqlSessionTemplate defaultSqlSessionTemplate(@Qualifier("sqlSessionFactorySecond") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
